﻿/*
 ***************************************************************************
 * Microsoft Visual C# .NET
 * 名称：       App_Input_MaterialApproveForm
 * 类型：       控制层
 * 功能说明：   物资设配-物资设备申领审批页面
 * 作者：       章 昕
 * 创建日期：   2007/10/26
 * 修改日期     修改者      修改内容
 * 
 * 
 * ---
 ***************************************************************************
*/

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Shpm.App.Input.Bean;
using log4net;
using Shpm.App.Input.Dao;
using Shpm.App.Commons.Db.Beans.Master;
using Shpm.App.Commons.Utils;
using Shpm.System.Validator;
using Shpm.System.Web.Control;
using Shpm.System;

public partial class App_Input_MaterialApproveForm : System.Web.UI.Page
{

    // log
    protected static ILog log = LogManager.GetLogger(typeof(App_Input_MaterialApproveForm));

    private const int COLUMN_STAT_TYPE = 0;

    // page load
    protected void Page_Load(object sender, EventArgs e)
    {
        txtAuditing.Attributes.Add("onchange", "showEmployeeName(this.id,'" + txtAuditingPerName.ClientID + "');");
        txtAuditing.Attributes.Add("onblur", "showEmployeeName(this.id,'" + txtAuditingPerName.ClientID + "');");
        //txtAuditingPerName.Attributes.Add("onfocus", "document.getElementById('"+ txtAuditing.ClientID + "').focus();");

        if (!IsPostBack)
        {
            // init page
            initPageControls();            
            this.MultiView1.SetActiveView(View1);            
        }
    }

    // before render
    void Page_PreRender(object sender, EventArgs e)
    {
        if (this.MultiView1.ActiveViewIndex == 0)
        {
            // 检索列表view
            gridViewRequisition.DataSource = ListMaterialReqData();
            gridViewRequisition.DataBind();
        }
        else
        {
            // 详细信息view            

        }
    }

    // 检索
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        ComValidateChecker vd = new ComValidateChecker();
        vd.Add(new CheckDate(txtStartDate.Text, new ComMessage("E0037", "开始日期")));
        vd.Add(new CheckDate(txtEndDate.Text, new ComMessage("E0037", "结束日期")));
        vd.Add(new CheckDateRange(txtStartDate.Text, txtEndDate.Text, new ComMessage("E0329", new string[] { "开始日期", "结束日期" })));
        if (!vd.DoValidator())
        {
            ((Design_MasterPage)this.Master).InfoMessage = vd.ErrorMessage;
            return;
        }

        ViewState["HidDept"] = lstDept.SelectedValue;
        ViewState["HidStat"] = lstStat.SelectedValue;
        ViewState["HidStartDate"] = txtStartDate.Text;
        ViewState["HidEndDate"] = txtEndDate.Text;
        gridViewRequisition.PageIndex = 0;
    }

    // 返回
    protected void btnBack_Click(object sender, EventArgs e)
    {
        this.MultiView1.SetActiveView(View1);
    }

    // page index change
    protected void gridViewRequisition_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        // 设置分页编号
        gridViewRequisition.PageIndex = e.NewPageIndex;
    }

    protected void gridViewRequisition_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        //Console.WriteLine(e.NewEditIndex);
        if (Request["x"] == null || Request["y"] == null)
        { return; }

        if (e.CommandName == "Details")
        {
            int index = Convert.ToInt32(e.CommandArgument);
            // Get the Key value from the GridView control.
            DataKey key = gridViewRequisition.DataKeys[index];

            if (!bindMaterialRequestionInfo(Convert.ToInt32(key.Value)))
            {
                ((Design_MasterPage)this.Master).InfoMessage =
                    HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0203").ToString().Replace("{0}", "物资申请");
                return;
            }
            lblReqId.Text = key.Value.ToString();
            this.MultiView1.SetActiveView(View2);
        }
    }

    // history on row data bind
    protected void gridViewHistory_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //if (string.IsNullOrEmpty(((MaterialRequsitionHistoryBean)e.Row.DataItem).AuditingTypeName))
            e.Row.Cells[COLUMN_STAT_TYPE].Text = "转批";
        }
    }

    // 批准
    protected void btnPass_Click(object sender, EventArgs e)
    {
        // 权限check
        if (!checkAuthority())
        {
            ((Design_MasterPage)this.Master).InfoMessage =
                HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0901").ToString();
            return;
        }

        string msgInfo = string.Empty;
        if (updApprove(MaterialRequisitionDao.REQUISITION_AUDITING_TYPE_PASS))
        {
            msgInfo = HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "I0002").ToString();
        }
        else
        {
            msgInfo = HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "I0029").ToString().Replace("{0}", "物资审批");
        }
        ((Design_MasterPage)this.Master).InfoMessage = msgInfo;

    }

    // 拒绝
    protected void btnReject_Click(object sender, EventArgs e)
    {
        // 权限check
        if (!checkAuthority())
        {
            ((Design_MasterPage)this.Master).InfoMessage =
                HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0901").ToString();
            return;
        }

        string msgInfo = string.Empty;
        if (updApprove(MaterialRequisitionDao.REQUISITION_AUDITING_TYPE_REJECT))
        {
            msgInfo = HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "I0002").ToString();
        }
        else
        {
            msgInfo = HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "I0029").ToString().Replace("{0}", "物资审批");
        }
        ((Design_MasterPage)this.Master).InfoMessage = msgInfo;
    }

    // 转批
    protected void btnWait_Click(object sender, EventArgs e)
    {
        // 权限check
        if (!checkAuthority())
        {
            ((Design_MasterPage)this.Master).InfoMessage =
                HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0901").ToString();
            return;
        }
        
        // 必须指定转批人
        ComValidateChecker vd = new ComValidateChecker();        
        vd.Add(new CheckRequired(txtAuditing.Text, new ComMessage("E0094", "转批人")));                
        if (!vd.DoValidator())
        {
            ((Design_MasterPage)this.Master).InfoMessage = vd.ErrorMessage;
            return;
        }

        // 指定的转批人权限check
        if (!checkAuditingPerson())
        {
            ((Design_MasterPage)this.Master).InfoMessage =
                HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "I0032").ToString().Replace("{0}", txtAuditing.Text);
            return;
        }

        updApprove(MaterialRequisitionDao.REQUISITION_AUDITING_TYPE_WAIT);
        //UpdateRequsitionStat
    }


    // list 物资申请列表
    private IList ListMaterialReqData()
    {
        IList list = null;
        MaterialRequisitionDao dao = new MaterialRequisitionDao();
        MaterialRequsitionBean beanMR = new MaterialRequsitionBean();

        if (!string.IsNullOrEmpty(Convert.ToString(ViewState["HidDept"])))
        { beanMR.RequisitionDeptmentName = Convert.ToString(ViewState["HidDept"]); }
        if (!string.IsNullOrEmpty(Convert.ToString(ViewState["HidStat"])))
        { beanMR.AuditingType = Convert.ToString(ViewState["HidStat"]); }
        if (!string.IsNullOrEmpty(Convert.ToString(ViewState["HidStartDate"])))
        { beanMR.BeginDate = DateUtils.convertToDate(Convert.ToString(ViewState["HidStartDate"])); }
        if (!string.IsNullOrEmpty(Convert.ToString(ViewState["HidEndDate"])))
        { beanMR.EndDate = DateUtils.convertToDate(Convert.ToString(ViewState["HidEndDate"])); }

        list = dao.ListMaterialRequsition(beanMR);
        return list;
    }

    // 取得物资申请详细数据
    private Boolean bindMaterialRequestionInfo(int requestionId)
    {
        MaterialRequsitionBean beanMR = new MaterialRequsitionBean();
        MaterialRequisitionDao dao = new MaterialRequisitionDao();
        beanMR.RequisitiobnId = requestionId;
        beanMR = dao.GetMaterialRequsition(beanMR);
        if (beanMR == null)
        { return false; }

        // bind data to page
        // 1. MaterialRequsition
        lblReqDept.Text = beanMR.RequisitionDeptmentName;
        lblReqPerson.Text = string.Format("{0} {1}", beanMR.EmployeeRequisitiobnId, beanMR.RequisitionPersonName);
        lblReqAuditing.Text = string.Format("{0} {1}", beanMR.EmployeeAuditingId, beanMR.AuditingPersonName);
        lblReqStat.Text = beanMR.AuditingTypeName;
        lblReqReason.Text = beanMR.RequisitionMemo;
        if (beanMR.RequisitionDate != null)
        { lblReqDate.Text = DateUtils.convertToString(beanMR.RequisitionDate.Value); }

        // 2. MaterialRequsitionDetail
        MaterialRequsitionDetailBean beanMRD = new MaterialRequsitionDetailBean();
        IList listDetail = null;
        beanMRD.RequisitiobnId = requestionId;
        listDetail = dao.ListRequsitionDetail(beanMRD);
        gridViewDetail.DataSource = listDetail;
        gridViewDetail.DataBind();

        // 3. History
        MaterialRequsitionHistoryBean beanMRH = new MaterialRequsitionHistoryBean();
        IList listHistory = null;
        beanMRH.RequisitiobnId = requestionId;
        listHistory = dao.ListRequsitionHistory(beanMRH);
        gridViewHistory.DataSource = listHistory;
        gridViewHistory.DataBind();

        txtAuditing.Text = "";
        txtMemo.Text = "";
        txtAuditingPerName.Text = string.Empty;
        //txtMemo.Text = beanMR.Memo == null ? "" : beanMR.Memo;

        lblReqId.Text = Convert.ToString(requestionId);
        if (!checkAuthority())
        {
            btnPass.Enabled = false;
            btnReject.Enabled = false;
            btnWait.Enabled = false;
        }

        return true;
    }    

    // 移交转批人权限check
    private Boolean checkAuditingPerson()
    {
        MaterialRequisitionDao dao = new MaterialRequisitionDao();
        MstEmployeeBean beanME = new MstEmployeeBean();
        beanME.EmployeeId = txtAuditing.Text;
        beanME = dao.GetEmployee(beanME);
        if (beanME == null)
        { return false; }
        
        // 部门check？ 仅转批给 上级？
        // TODO：

        return true;
    }

    // 更新权限check
    private Boolean checkAuthority()
    {
        SysUserManager manager = new SysUserManager(Context);
        SysUserBean sysUserBean = manager.getSysUserBean();
        MstSysUserBean mstSysUserBean =
            sysUserBean == null ? null : sysUserBean.getMstSysUserBean();
        MstEmployeeBean mstEmpBean =
            sysUserBean == null ? null : sysUserBean.getEmployeeBean();
        string loginId = mstSysUserBean == null ? "" : mstSysUserBean.SysUserId;
        string emplyId = mstSysUserBean == null ? "" : mstSysUserBean.EmployeeId;
        string emplyRole = mstEmpBean == null ? "" : mstEmpBean.Role;
        string emplyJob = mstEmpBean == null ? "" : mstEmpBean.EmployeeJob;
        string emplyLev = mstEmpBean == null ? "" : mstEmpBean.EmployeeLevel;

        MaterialRequisitionDao dao = new MaterialRequisitionDao();
        MaterialRequsitionBean beanMR = new MaterialRequsitionBean();
        beanMR.RequisitiobnId = Convert.ToInt32(lblReqId.Text);
        beanMR = dao.GetMaterialRequsition(beanMR);
        if (beanMR == null || string.IsNullOrEmpty(beanMR.EmployeeAuditingId)
            ||!emplyId.Equals(beanMR.EmployeeAuditingId))
        { return false; }
        
        return true;
    }

    // 更新物资申请记录--审批
    private Boolean updApprove(string auditingType)
    {
        if (string.IsNullOrEmpty(lblReqId.Text))
        { return false; }

        SysUserManager manager = new SysUserManager(Context);
        SysUserBean sysUserBean = manager.getSysUserBean();
        MstSysUserBean mstSysUserBean =
            sysUserBean == null ? null : sysUserBean.getMstSysUserBean();
        MstEmployeeBean mstEmpBean =
            sysUserBean == null ? null : sysUserBean.getEmployeeBean();
        string loginId = mstSysUserBean == null ? "" : mstSysUserBean.SysUserId;
        string emplyId = mstSysUserBean == null ? "" : mstSysUserBean.EmployeeId;
        string emplyRole = mstEmpBean == null ? "" : mstEmpBean.Role;
        string emplyJob = mstEmpBean == null ? "" : mstEmpBean.EmployeeJob;
        string emplyLev = mstEmpBean == null ? "" : mstEmpBean.EmployeeLevel;

        MaterialRequisitionDao dao = new MaterialRequisitionDao();
        MaterialRequsitionBean beanMR = new MaterialRequsitionBean();
        beanMR.RequisitiobnId = Convert.ToInt32(lblReqId.Text);
        beanMR = dao.GetMaterialRequsition(beanMR);
        if (beanMR == null)
        { return false; }

        beanMR.Memo = txtMemo.Text;
        beanMR.AuditingType = auditingType;
        beanMR.UserId = loginId;    
        if (MaterialRequisitionDao.REQUISITION_AUDITING_TYPE_WAIT.Equals(auditingType))
        {
            // update Requisition and History
            MaterialRequsitionHistoryBean beanMRH = new MaterialRequsitionHistoryBean();
            beanMRH.RequisitiobnId = beanMR.RequisitiobnId;
            beanMRH.EmployeeId = beanMR.EmployeeAuditingId;
            beanMRH.Memo = txtMemo.Text;            
            beanMRH.UserId = loginId;
            beanMR.EmployeeAuditingId = txtAuditing.Text;
            dao.UpdateRequstionStat(beanMR,beanMRH);
        }
        else
        {
            // update Requisition            
            beanMR.EmployeeAuditingId = emplyId;                    
            dao.UpdateRequsitionStat(beanMR);
        }
        bindMaterialRequestionInfo(beanMR.RequisitiobnId.Value);

        return true;
    }

    // bind common catalog data 
    private void initPageControls()
    {
        MaterialRequisitionDao dao = new MaterialRequisitionDao();
        CommonDictionaryBean beanComDict = new CommonDictionaryBean();
        IList lstCat = null;

        // 申请部门
        //log.Fatal("\n ***** get ROOM_TYPE catalog *****");
        //beanComDict.Catalog = "ROOM_TYPE";
        //lstCat = dao.FindByCatalog(beanComDict);
        //lstRoomType.Items.Clear();
        //lstRoomType.Items.Add("");
        //bindDataToListControl("lstRoomType", lstCat);
        lstCat = dao.ListDepartment(new MstDepartmentBean());
        lstDept.DataTextField = "DepartName";
        lstDept.DataValueField = "DepartId";
        lstDept.DataSource = lstCat;
        lstDept.DataBind();
        lstDept.Items.Insert(0, "");

        // 审批状态        
        beanComDict.Catalog = "T_MATERIAL_REQUISITION.AUDINGTING_TYPE";
        lstCat = dao.FindByCatalog(beanComDict);
        lstStat.Items.Clear();
        lstStat.Items.Add("");
        bindDataToListControl("lstStat", lstCat);

    }

    // bind db data to selected controls
    private void bindDataToListControl(string ControlId, IList LstData)
    {
        if (LstData == null || LstData.Count == 0) return;

        foreach (CommonDictionaryBean bean in LstData)
        {
            if (this.Master.FindControl("ContentPlaceHolder1").FindControl(ControlId) is DropDownList)
            {
                ((DropDownList)this.Master.FindControl("ContentPlaceHolder1").FindControl(ControlId)).Items.Add(new ListItem(bean.Content, bean.DictNo.ToString()));
            }
            else if ((this.Master.FindControl("ContentPlaceHolder1").FindControl(ControlId) is CheckBoxList)
                || (this.Master.FindControl("ContentPlaceHolder1").FindControl(ControlId) is RadioButtonList))
            {
                ((ListControl)this.Master.FindControl("ContentPlaceHolder1").FindControl(ControlId)).Items.Add(new ListItem(bean.Content, bean.DictNo.ToString()));
            }
        }
    }
}
